/**
 * Module dependencies.
 */

var express = require('express'),
    routes = require('./routes'),
    http = require('http'),
    path = require('path'),
    flash=require('connect-flash'),
    ejs = require('ejs'),
    config=require('./config'),
    MongoStore = require('connect-mongo')(express),
    multer  = require('multer'),
    // settings = require('./settings'),
    shop_goods = require('./routes/shop_goods');
    activity = require('./routes/activity');
    material = require('./routes/material');
    applyfor = require('./routes/applyfor');
    lottery = require('./routes/lottery');
    app = express();

app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(flash());
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(express.cookieParser());//cookie解析中间件
app.use(express.session({       //提供会话支持
    secret:config.cookieSecret,
    cookie:{maxAge:1000*60*60*10},//10个小时
    store:new MongoStore({
        url:config.db_url
        //db:config.db
    })
}))
app.use(multer({
    dest: './public/uploads/',
    limits: {
        fieldNameSize: 100,
        files: 1,
        fileSize: 2048*1024//最大上传2M图片
    }/*,
     onFileSizeLimit: function (file) {
     console.log('Failed: ', file.originalname);
     fs.unlink('./uploads/' + file.path) // delete the partially written file
     }*/
}));//处理文件上传
app.use(function(req,res,next){       //注册全局变量
    var err = req.flash('error');
    var success = req.flash('success');
    res.locals.user = req.session.user;
    res.locals.error= err.length ? err : null;
    res.locals.success = success.length ? success : null;
    next();
});
app.use(function(req,res,next){
     var url=req.path;
     console.log(url);
     var reg=url.indexOf('.')<0&&url!='/'&&!req.session.user;
     if(reg){
         //req.flash('error','你没有登陆，不能操作');
         return res.redirect("/");
     }

     next();
})

app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));

// development only
if ('development' == app.get('env')) {
  app.use(express.errorHandler());
}

routes(app);
shop_goods(app);
activity(app);
applyfor(app);
lottery(app);
material(app);

http.createServer(app).listen(3000);